# config/error_handlers.py

import traceback
from flask import jsonify, current_app
from sqlalchemy.exc import SQLAlchemyError
from marshmallow import ValidationError

def handle_expired_error(e):
    """处理 JWT token 过期错误"""
    error_message = 'Token has expired'
    current_app.logger.warning(
        f"Token Expired Error: {error_message}\n"
        f"Error Details: {str(e)}"
    )
    return jsonify({'message': error_message}), 401

def handle_database_error(e):
    """处理数据库错误"""
    # 获取完整的异常堆栈
    stack_trace = traceback.format_exc()
    
    # 构建错误信息
    error_message = 'Database error occurred'
    if isinstance(e, SQLAlchemyError):
        # 对于 SQLAlchemy 错误，获取具体的错误信息
        error_details = str(e.__dict__.get('orig', e))
    else:
        error_details = str(e)
    
    # 记录详细的错误日志
    current_app.logger.error(
        f"Database Error: {error_message}\n"
        f"Error Type: {type(e).__name__}\n"
        f"Error Details: {error_details}\n"
        f"Stack Trace:\n{stack_trace}"
    )
    
    # 返回给客户端的信息（不包含敏感信息）
    return jsonify({'message': error_message}), 500

def handle_validation_error(e):
    """处理验证错误"""
    if isinstance(e, ValidationError):
        error_messages = e.messages
    else:
        error_messages = str(e)
    
    # 记录验证错误
    current_app.logger.warning(
        f"Validation Error occurred:\n"
        f"Error Details: {error_messages}"
    )
    
    return jsonify({'message': error_messages}), 400

def handle_not_found_error(e):
    """处理 404 错误"""
    error_message = 'Resource not found'
    current_app.logger.info(
        f"Not Found Error: {error_message}\n"
        f"Path: {current_app.request.path}\n"
        f"Method: {current_app.request.method}"
    )
    return jsonify({'message': error_message}), 404

def handle_method_not_allowed(e):
    """处理 405 Method Not Allowed 错误"""
    error_message = 'Method not allowed'
    current_app.logger.warning(
        f"Method Not Allowed Error: {error_message}\n"
        f"Path: {current_app.request.path}\n"
        f"Method: {current_app.request.method}"
    )
    return jsonify({'message': error_message}), 405

def handle_general_error(e):
    """处理通用错误"""
    stack_trace = traceback.format_exc()
    error_message = 'An unexpected error occurred'
    
    # 记录详细的错误日志
    current_app.logger.error(
        f"Unhandled Error: {error_message}\n"
        f"Error Type: {type(e).__name__}\n"
        f"Error Details: {str(e)}\n"
        f"Stack Trace:\n{stack_trace}"
    )
    
    return jsonify({'message': error_message}), 500